'use strict';

angular.module('myApp.calander', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/calander', {
    templateUrl: 'calander/index.html',
    controller: 'CalanderCtrl'
  });
  $routeProvider.when('/detail', {
    templateUrl: 'calander/detail.html',
    controller: 'DetailCtrl'
  });
}])

.controller('CalanderCtrl', [
    '$scope', '$routeParams', '$location', '$http',
    function ($scope, $routeParams, $location, $http) {
        if ($scope.signinUser.isSignin === false) {
            $location.url('/signin?done=' + $location.url());
        }
        var current = new Date();
        $scope.date = {
            year: current.getFullYear(),
            month: current.getMonth() + 1,
            date: current.getDate()
        };
        $scope.days = getDays();

        // var id = parseInt($routeParams.id) || 0;
        // var apiUri = '/dianping/api/business/get_single_business';
        // var params = { business_id: id };
        // $http.get(apiUri, { params: params }).success(function (data) {
        //     console.log('get_single_business', data);
        //     var shop = data.businesses[0];
        //     shop.name = shop.name.replace('(这是一条测试商户数据，仅用于测试开发，开发完成后请申请正式数据...)', '');
        //     $scope.shop = shop;
        //     var tip = '<big>' + shop.name + '</big></br>' + shop.address;
        //     initMap(shop.longitude, shop.latitude, tip);
        // });

        // apiUri = '/dianping/api/review/get_recent_reviews';
        // params = { business_id: id };
        // $http.get(apiUri, { params: params }).success(function (data) {
        //     // console.log('get_recent_reviews', data);
        //     $scope.reviews = data.reviews;
        // });
    }
])

.controller('DetailCtrl', [
    '$scope', '$routeParams', '$location', '$http',
    function ($scope, $routeParams, $location, $http) {
        if ($scope.signinUser.isSignin === false) {
            $location.url('/signin?done=' + $location.url());
        }
        var id = parseInt($routeParams.id) || 0;
        var date = new Date();
        $scope.date = {
            year: date.getFullYear(),
            month: date.getMonth() + 1,
            date: date.getDate()
        };
        $scope.blog = {
            energy: 0,
            actions: [],
            mood: 0,
            summary: ''
        };
        $scope.blog = {
            energy: 2252,
            actions: [{
                type: 'Running',
                time: 10,
                // count: 3.0,
                energy: 1314
            }, {
                type: 'Swiming',
                time: 30,
                // count: 1.0,
                energy: 1252
            }],
            mood: 1,
            summary: 'Bodybuilding is the use of progressive resistance exercise to control and develop one\'s musculature.[1] An individual who engages in this activity is referred to as a bodybuilder. In competitive amateur and professional bodybuilding, bodybuilders appear in lineups doing specified poses, and later perform individual posing routines, for a panel of judges who rank competitors based on criteria such as symmetry, muscularity and conditioning. '
        };

        if ('' == $scope.blog.summary) {
            $scope.showSummaryEdit = true;
        } else {
            $scope.showSummaryEdit = false;
        }

        
        $scope.actionTypes = ['跑步', '游泳', '暴走'];
        var times = [];
        for (var i = 5; i <= 120; i += 5) {
            times.push(i);
            if (i > 25) {
                i += 5;
            }
        }
        $scope.times = times;

        
        $scope.currentActionIndex = 0;

        $scope.showNew = false;


        $scope.newItem = function () {
            if ($scope.blog.actions.length >= 3) {
                alert('最多填写3项运动');
                return;
            }
            $scope.showNew = true;
            $scope.newActionData = {
                type: '跑步',
                time: 30
            };
        };

        $scope.addItem = function () {
            $scope.newActionData.energy = getEnergy($scope.newActionData);
            $scope.blog.actions.push($scope.newActionData);
            $scope.blog.energy = sumEnergy($scope.blog.actions);
            $scope.showNew = false;
        };

        $scope.editItem = function (id) {
            // 隐藏当前编辑状态的记录
            if (id != $scope.currentActionIndex) {
                $scope.blog.actions[$scope.currentActionIndex].showEdit = false;
            }
            $scope.blog.actions[id].showEdit = true;
            $scope.selectedAction = $scope.blog.actions[id];
            $scope.currentActionIndex = id;
        };

        $scope.saveItem = function (id) {
            console.log('save', id, $scope.selectedAction);
            $scope.selectedAction.energy = getEnergy($scope.selectedAction);
            $scope.blog.actions[id] = $scope.selectedAction;
            $scope.blog.actions[id].showEdit = false;
            $scope.blog.energy = sumEnergy($scope.blog.actions);
        };

        $scope.deleteItem = function (id) {
            if (confirm('确认删除此项?')) {
                $scope.blog.actions.splice(id, 1);
                $scope.blog.energy = sumEnergy($scope.blog.actions);
            }
        };

        if ($scope.blog.actions.length === 0) {
            $scope.newItem();
        }


        $scope.moods = [{
            score: 2,
            en: 'exciting',
            cn: '兴奋'
        }, {
            score: 1,
            en: 'happy',
            cn: '愉悦'
        }, {
            score: 0,
            en: 'normal',
            cn: '一般'
        },{
            score: -1,
            en: 'poor',
            cn: '不佳'
        },{
            score: -2,
            en: 'bad',
            cn: '糟糕'
        }];

        $scope.setMood = function (score) {
            // console.log('changeMood', score);
            $scope.blog.mood = score;
            for (var i = 0; i < $scope.moods.length; i++) {
                if ($scope.moods[i].score == $scope.blog.mood) {
                    $scope.moods[i].isActive = true;
                } else {
                    $scope.moods[i].isActive = false;
                }
            }
        };

        $scope.setMood($scope.blog.mood);


        $scope.editSummary = function () {
            // 隐藏当前编辑状态的记录
            $scope.showSummaryEdit = true;
        };

        $scope.saveSummary = function () {
            console.log('saveSummary', $scope.blog.summary);
            if ('' == $scope.blog.summary) {
                alert('Please write something you like...');
                return;
            }
            $scope.showSummaryEdit = false;
        };


        $scope.days = getDays();
    }
]);


function getDays () {
    var days = [];
    var current = new Date();
    var year = current.getFullYear();
    var month = current.getMonth() + 1;
    var day = current.getDate();

    for (var i = 0; i < getFirstDay(current); i++) {
        days.push({
            dateString: '',
            date: '',
            blog: {}
        });
    }
    for (var i = 1; i <= getLastDate(current); i++) {
        var energy = 0;
        if (i < day) {
            energy = Math.floor(Math.random() * 3000);
        }
        days.push({
            dateString: year + '-' + month + '-' + i,
            date: i,
            blog: { energy: energy }
        });
    }

    return days;
}


function getFirstDay (date) {
    var year = date.getFullYear();
    var month = date.getMonth();
    var date = new Date(year, month, 1);
    return date.getDay();
}


function getLastDate (date) {
    var year = date.getFullYear();
    var month = date.getMonth();
    var days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    if (year % 4 == 0) {
        days[1] = 29;
    }
    return days[month];
}


function getEnergy (obj) {
    var energyPerMin = 100;
    return obj.time * energyPerMin;
}


function sumEnergy (arr) {
    var sum = 0;
    for (var i = 0; i < arr.length; i++) {
        sum += arr[i].energy;
    }
    return sum;
}